<template>
  <div :class="ns.b()" @scroll.passive="handleScroll">
    <div v-if="keyword" :class="ns.e('list')" v-spin="loading">
      <template v-if="searchResultList.length">
        <div v-for="result in searchResultList" :key="result.id" :class="ns.e('result-wrapper')">
          <div :class="ns.e('name')" v-html="result.name" @click="handleCompanyClick(result)" />
          <div :class="ns.e('labels')" v-if="result.labels">
            <span v-for="label in result.labels" :key="label.name" :class="ns.e('label')" :style="{ color: label.color, backgroundColor: label.bgColor }">{{ label.name }}</span>
          </div>
          <template v-if="result?.matches?.length">
            <div :class="ns.e('match')" v-for="match in result.matches">
              <span :class="ns.e('match-label')">{{ match.label }}：</span>
              <span v-html="match.value"/>
            </div>
          </template>

          <div v-if="result?.groupIds && result.groupIds?.length" :class="ns.e('monitored')">
            <span>已监控</span>
          </div>
          <div v-else :class="ns.e('monitor')" @click.stop="addMemberToGroup(result)">
            <i :class="ns.e('monitor-icon-add')" />
            <span>监控</span>
          </div>
        </div>
      </template>
      <template v-else-if="!loading">
        <vc-nodata :type="202"/>
      </template>
    </div>
    <template v-else>
      <div :class="ns.e('history')">
        <div :class="ns.e('title')">
          最近搜索
          <i :class="ns.e('icon-delete')" title="清空" @click="removeSearchHistory" />
        </div>
        <div :class="ns.e('wrapper')">
          <span v-for="item in searchHistoryList" :key="item.id" :class="ns.e('item')"
            @click="handleCompanyClick(item)">{{ item.name }}</span>
        </div>
      </div>
      <div :class="ns.e('hot')">
        <div :class="ns.e('title')">热门搜索</div>
        <div :class="ns.e('wrapper')">
          <span v-for="item in hotSearchList" :key="item.id" :class="ns.e('item')"
            @click="handleCompanyClick(item)">{{ item.name }}</span>
        </div>
      </div>
    </template>
  </div>
</template>

<script setup lang="ts">
import { useNamespace } from 'vc/src/use';
import { useSearchHistory, useHotSearch, useCompanySearch } from './useEnterpriseSearch';
import type { ISerachItem } from './types';
import { getGroupListAndCompanyId, addMember } from '../apis';
import { toF9 } from '@/utils';

interface ISearchContentProps {
  keyword: string | number;
  visible: boolean;
  from: string;
  enterCount: number;
}

const { keyword, from = '', enterCount = 0 } = defineProps<ISearchContentProps>();

const emit = defineEmits(['update:visible', 'handleSearch']);

const ns = /* hoist-static*/ useNamespace('search-inner');
defineOptions({ name: ns.b() });

/** 最近搜索 */
const {
  searchHistoryList,
  getSearchHistoryList,
  setSearchHistory,
  removeSearchHistory
} = useSearchHistory();

/** 热门搜索 */
const { hotSearchList, getHotSearchList } = useHotSearch();

/** 搜索结果 */
const {
  loading,
  hasMore,
  searchParams,
  searchResultList,
  getSearchResultList
} = useCompanySearch();

const timer = ref();
const initSearch = (val: string | number) => {
  searchParams.wd = val;
  searchParams.offset = 0;
  searchResultList.value = [];
  getSearchResultList();
};

/** 监听keyword变化：为空则获取历史和热搜，不为空则获取搜索数据 */
watch(
  () => keyword,
  (val) => {
    if (val) {
      /** 搜索节流 */
      if (timer.value) clearTimeout(timer.value);
      timer.value = setTimeout(() => initSearch(val), 500);
    } else {
      getSearchHistoryList();
      getHotSearchList();
    }
  },
  { immediate: true }
);

/** 监听回车事件，页头搜索回车默认进入第一个搜索结果f9 */
watch(
  () => enterCount,
  () => {
    if (from === 'pageHeader' && searchResultList.value.length) {
      setSearchHistory(searchResultList.value[0]);
      const cid = searchResultList.value[0].id;
      toF9(cid);
    }
  }
);

onBeforeUnmount(() => clearTimeout(timer.value));

/** 滚动到底部继续加载 */
const handleScroll = (e: Event) => {
  if (keyword) {
    const { clientHeight, scrollTop, scrollHeight } = e.target as HTMLElement;
    if (clientHeight + scrollTop >= scrollHeight - 30 && !loading.value && hasMore.value) {
      getSearchResultList();
    }
  }
};

/** 点击公司：跳转+存搜索历史 */
const handleCompanyClick = (result: ISerachItem) => {
  setSearchHistory(result);
  emit('handleSearch', result);
};

const addMemberToGroup = async (result: ISerachItem) => {
  const res = await getGroupListAndCompanyId();
  if (res?.items?.length) {
    const defaultGroup = res.items.find((item) => item.isDefault === 1) || res.items[0];
    const addRes = await addMember(defaultGroup.id, [result.id]);
    if (addRes.code === 200) {
      result.groupIds = [defaultGroup.id + ''];
      setSearchHistory(result);
    }
  }
};
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
